import cs1705.*;
import cs1705.web.*;
import java.net.*;

// -------------------------------------------------------------------------
/**
 *  A simple WebBot task that creates a WebBot and uses it to
 *  print all the links on a web page.
 * 
 *  @author  Stephen Edwards
 *  @version 2009.03.19
 */
public class LinkFinderTask
    implements RobotTask
{
    //~ Instance/static variables .............................................

    WebBot bot = null;


    //~ Methods ...............................................................

    // ----------------------------------------------------------
    /**
     * Creates a WebBot and uses it to list all the links on a web page.
     */
    public void task()
    {
        bot = new WebBot("http://www.vt.edu/");

        bot.setOutputIsHtml(true);
        bot.out().print("<p>title => ");
        bot.echoPageTitle();
        bot.out().println("</p><ul>");

        bot.advanceToNextLink();
        while (bot.isLookingAtLink())
        {
            URI uri = bot.getLinkURI();
            // Sometimes, anchor tags do not contain href values
            if (uri != null)
            {
                URI fullUri = bot.resolveURIFromPage(uri.toString());
                bot.out().println("<li>next link => <a href=\""
                    + fullUri + "\">" + uri + "</a></li>");
            }
            bot.advanceToNextLink();
        }
        bot.out().println("</ul>");
    }


    // ----------------------------------------------------------
    /**
     * This method provides access to the robot that carries out this
     * task.  Change the return type of this method if you write
     * your own custom robot class.
     * @return The robot used by this task.
     */
    public WebBot getRobot()
    {
        return bot;
    }
}
